import axios, { FormData } from '@ohos/axios'
import { promptAction } from '@kit.ArkUI';
import { AnyObject } from '../../models/Http';
import { useUserStore } from '../../store/modules/user';
import { loadingManager } from './loadingManager';
import fs from '@ohos.file.fs';

const request = axios.create({
  baseURL:'http://192.168.17.1:18080'
})

request.interceptors.request.use(
  (config) => {
    // 判断是否需要显示loading（默认显示）
    // 从config中读取showLoading配置
    const showLoading = (config as any).showLoading !== false
    if (showLoading) {
      loadingManager.show()
    }
    
    // 直接从用户store读取token
    try {
      const userStore = useUserStore()
      const token = userStore.token
      if (token) {
        if (!config.headers) {
          (config as any).headers = {}
        }
        (config.headers as any)['Authorization'] = `${token}`
      }
    } catch (error) {
      console.error('从store读取token失败:', error)
    }

    return config
  }
)


request.interceptors.response.use(
  (response) => {
    // 隐藏loading（请求成功）
    const showLoading = (response.config as any).showLoading !== false
    if (showLoading) {
      loadingManager.hide()
    }
    
    // 根据后端接口,只有200000才是正确的返回状态
    console.log("[请求拦截器]返回的响应",JSON.stringify(response.data))
    if(response.data.code === 200000) {
      const data = response.data.data
      const msg = response.data.msg
      return response.data.data;
    }else {
      const msg = response.data.msg
      promptAction.showToast({ message: msg })
      return Promise.reject(msg)
    }
  },
  (error) => {
    // 隐藏loading（请求失败）
    // 从error对象中获取config来判断是否需要隐藏loading
    const config = (error && (error as any).config) ? (error as any).config : null
    const showLoading = !config || (config as any).showLoading !== false
    if (showLoading) {
      loadingManager.hide()
    }
    
    try {
      const resp = (error && (error as any).response) ? (error as any).response : null
      const serverMsg = resp && resp.data && resp.data.msg ? resp.data.msg : null
      const messageToShow = serverMsg || error.message || '请求失败'
      promptAction.showToast({ message: messageToShow });
      return Promise.reject(serverMsg || error)
    } catch (_) {
      promptAction.showToast({ message: '请求失败' });
      return Promise.reject(error)
    }
  }
)


// 扩展参数接口，支持showLoading配置
export interface RequestConfig {
  showLoading?: boolean  // 默认为true，设置为false时不显示loading
}

export default  class  Http {
  get<T>(url:string, params?:AnyObject, config?: RequestConfig) {
    return request.get<any,T>(url, {
      params,
      showLoading: config?.showLoading ?? true  // 默认为true
    } as any);
  }

  post<T>(url:string, data?:AnyObject, config?: RequestConfig) {
    return request.post<any,T>(url, data, {
      showLoading: config?.showLoading ?? true  // 默认为true
    } as any);
  }

  put<T>(url:string, data?:AnyObject, config?: RequestConfig) {
    return request.put<any,T>(url, data, {
      showLoading: config?.showLoading ?? true  // 默认为true
    } as any);
  }

  delete<T>(url:string, params?:AnyObject, config?: RequestConfig) {
    return request.delete<any,T>(url, {
      params,
      showLoading: config?.showLoading ?? true  // 默认为true
    } as any);
  }

}